package com.api.service.v1;

import com.admin.entity.Onandofflinetime;
import com.admin.entity.Station;
import com.admin.entity.Terminal;
import com.admin.entity.TerminalKey;
import com.admin.enums.StationType;
import com.admin.enums.TerminalLineType;
import com.admin.mapper.OnandofflinetimeMapper;
import com.admin.mapper.StationMapper;
import com.admin.mapper.TerminalKeyMapper;
import com.admin.mapper.TerminalMapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bean.ResponseBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 安卓心跳信息
 * @author  lgh
 */

@SuppressWarnings("ALL")
@Service
public class HeartAPIService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private TerminalMapper terminalMapper;

    @Autowired
    private StationMapper stationMapper;

    @Autowired
    private TerminalKeyMapper terminalKeyMapper;

    @Autowired
    private OnandofflinetimeMapper onandofflinetimeMapper;

    /**
     * 处理心跳
     *   1.更新终端表的IP
     *   2.修改终端表的在线状态
     *   3.增加秘钥表使用记录
     * @param mac
     * @param ip
     * @return
     */
    public ResponseBean handlerHeart(String mac, String ip) {
        Object redisMac = redisTemplate.boundValueOps("heart_" + mac);
        //更新终端ip信息
        QueryWrapper q = new QueryWrapper();
        q.eq("terminal_mac", mac);
        Terminal t = terminalMapper.selectOne(q);
        if (t == null) {
            return new ResponseBean(404, "找不到终端", null);
        }
        if (ip != null && ip.trim().length() > 0 && t.getTerminalIp() != null && !t.getTerminalIp().equals(ip)) {
            t.setTerminalIp(ip);
            terminalMapper.updateById(t);
        }
        //更新redis,如果30秒没有访问，则会销毁
        redisTemplate.boundValueOps("heart_" + mac).set("1", 30, TimeUnit.SECONDS);

        //修改数据库中心跳状态为在线
        if (redisMac == null) {
            t.setTerminalLine(TerminalLineType.在线.name());
            terminalMapper.updateById(t);
        }
        //如果是解锁状态则添加记录
        Station  station = stationMapper.selectById(t.getTerminalStation());
        if (StationType.租赁.name().equals(station.getStationModel()) && "正常".equals(t.getTerminalLock()))
        {
            //增加上线时间
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("terminal", t.getTerminalId());
            queryWrapper.eq("countTime", 0);
            long total = onandofflinetimeMapper.selectPage(new Page(1, 1), queryWrapper).getTotal();
            if (total == 0) {

                Date date = new Date();
                Onandofflinetime onandofflinetime = new Onandofflinetime();
//                onandofflinetime.setOnlinetime(date);
                onandofflinetime.setTerminal(t.getTerminalId());
                onandofflinetime.setToCount(0);
                onandofflinetime.setStation(station.getStationId());
                onandofflinetime.setMacLocal(t.getTerminalMac());
                onandofflinetimeMapper.insert(onandofflinetime);
            }
        }
        //返回
        String tip = "";
        if (StationType.租赁.name().equals(station.getStationModel()))
        {
            tip = station.getStationLocktip();
        }

        Map map = new HashMap();
        map.put("locktip",tip);
        map.put("status",("正常".equals(t.getTerminalLock())?0:1));
        return new ResponseBean(200, "success", map);
    }

    /**
     * 终端下线
     * @param mac
     */
    public void offLine(String mac) {
        QueryWrapper q = new QueryWrapper();
        q.eq("terminal_mac", mac);
        Terminal t = terminalMapper.selectOne(q);
        if (t!=null)
        {
            t.setTerminalLine(TerminalLineType.离线.name());
            terminalMapper.updateById(t);
        }
    }

    /**
     * 密钥过期修改密钥状态  以及终端状态
     * @param terminalKeyId
     */
    public void PasswordKey(String terminalKeyId) {
        //根据id找出密钥这条数据
        TerminalKey tk = terminalKeyMapper.selectById(terminalKeyId);
        //密钥绑定的终端
        Terminal t=terminalMapper.selectById(tk.getTerminalKey());
        if (tk!=null)
        {
            tk.setTerminalKeyStatus("已过期");
            t.setTerminal_key_id(0);
            t.setTerminal_key("");
            t.setTerminalLock("已锁定");
            t.setTerminalLine("离线");
            terminalKeyMapper.updateById(tk);
            terminalMapper.updateById(t);
        }
    }


}
